package com.adingxiong.cft.controller;

import com.adingxiong.cft.common.entity.ImageCode;
import com.adingxiong.cft.errors.Assert;
import com.adingxiong.cft.result.Result;
import com.adingxiong.cft.util.ImageCodeUtil;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import static org.apache.http.nio.reactor.ssl.SSLIOSession.SESSION_KEY;

/**
 * @ClassName ComController
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/10/15 13:32
 **/
@RestController
@Api(tags = "工具模块")
@RequestMapping("/util")
public class ComController {

    private SessionStrategy sessionStrategy  = new HttpSessionSessionStrategy() ;


    @GetMapping("/code/img")
    @ApiOperation(value = "获取图形验证码,有效期一分钟")
    public void createImgCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = ImageCodeUtil.createIamgeCode();
        sessionStrategy .setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
        ImageIO.write(imageCode.getImage(),"jpeg",response.getOutputStream());
    }

    @GetMapping("/code/valid")
    public Result codeValidate(
            @ApiParam(value = "imgCode",name = "图文验证码",required = true) @RequestParam(value = "imgCode") String imgCode,
            HttpServletRequest request
    ){
        ImageCode code = (ImageCode) sessionStrategy.getAttribute(new ServletWebRequest(request),SESSION_KEY);
        if(StringUtils.isEmpty(imgCode)){
            return Result.imgcodeError();
        }
        if(code == null){
            Assert.fail("验证码不存在");
        }
        if(code.isExpire()){
            sessionStrategy.removeAttribute(new ServletWebRequest(request),SESSION_KEY);
            Assert.fail("验证码已过期");
        }
        if(!StringUtils.equalsIgnoreCase(code.getCode(),imgCode)){
            Assert.fail("验证码输入错误");
        }
        return Result.success(true);
    }
}
